package com.chenju.easyshotjava.core;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {
    public static List<String> getTestCaseIds(FileInputStream fis) {
        List<String> testCaseIds = new ArrayList<>();
        try {
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            int columnIndex = getTargetColumnIndex(sheet);

            if (columnIndex != -1) { // 如果找到目标列
                for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                    Row row = sheet.getRow(rowIndex);
                    String cellValue = getCellStringValue(row, columnIndex);
                    if (cellValue != null && !cellValue.trim().isEmpty()) {
                        testCaseIds.add(cellValue.trim());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return testCaseIds;
        }
        return testCaseIds;
    }

    private static int getTargetColumnIndex(Sheet sheet) {
        Row titleRow = sheet.getRow(0);
        if (titleRow == null) {
            return -1;
        }
        for (int i = 0; i < titleRow.getLastCellNum(); i++) {
            String cellValue = getCellStringValue(titleRow, i);
            if ("测试案例编号".equals(cellValue) || "编号".equals(cellValue)) {
                return i;
            }
        }
        return -1;
    }

    private static String getCellStringValue(Row row, int columnIndex) {
        if (row == null) {
            return null;
        }
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue();
            case NUMERIC -> String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
            default -> null;
        };
    }
}
